package org.springframework.howelly.services;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.howelly.model.Categoria;
import org.springframework.howelly.model.Gasto;
import org.springframework.howelly.utils.Constants;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("categoriaService")
@Repository
public class JpaCategoriaService implements CategoriaService {

    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
	this.em = em;
    }

    @SuppressWarnings("unchecked")
    @Transactional
    public List<Categoria> findCategoriasByObra(long obraId) {
	List<Categoria> result = em.createQuery("select c from Categoria c where c.obra.id =:obraId").setParameter(
		"obraId", obraId).getResultList();
	return result;
    }

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public List<Gasto> findGastosWithCategoria(String categoria, long obraId) {
	if (categoria != null) {
	    List<Gasto> result = em
		    .createQuery(
			    "select g from Gasto g  where g.obra.id =:obraId and g.expenseType =:expenseType and g.categoriaName =:categoria")
		    .setParameter("expenseType", Constants.GASTO).setParameter("obraId", obraId).setParameter(
			    "categoria", categoria).getResultList();
	    return result;
	} else {
	    return null;
	}
    }

    @Transactional(readOnly = true)
    public BigDecimal calculateTotalForCategory(List<Gasto> gastosWithCategories) {
	double total = 0;
	for (Gasto gasto : gastosWithCategories) {
	    total += gasto.getPrice().doubleValue();
	}
	return new BigDecimal(total);
    }

}
